const { http } = require('./http.js');

/**
 * 笔记服务
 */
class NoteService {
  /**
   * 根据题目ID获取用户笔记
   * @param {string|number} questionId 题目ID
   * @returns {Promise<Array>} 笔记列表
   */
  async getNoteByQuestionId(questionId) {
    if (!questionId) {
      return [];
    }

    try {
      const res = await http.get(`/wjq/note/listByQuestionId/${questionId}`);
      
      if (res && res.data && Array.isArray(res.data)) {
        return res.data.map(note => ({
          id: note.id,
          questionId: questionId,
          content: note.content || '',
          createTime: note.createTime || note.create_time || '',
          updateTime: note.updateTime || note.update_time || '',
          userId: note.userId || note.user_id || ''
        }));
      }
      
      return [];
    } catch (error) {
      console.error('获取笔记失败:', error);
      return [];
    }
  }

  /**
   * 获取用户的所有笔记列表
   * @param {Object} params 查询参数
   * @returns {Promise<Array>} 笔记列表
   */
  async getNoteList(params = {}) {
    console.log('noteService.getNoteList 开始执行，参数:', params);
    
    try {
      // 获取当前用户ID
      const { getUserId } = require('./userManager.js');
      const userId = getUserId();
      
      console.log('获取到的用户ID:', userId);
      
      if (!userId) {
        console.warn('用户未登录，无法获取笔记列表');
        return [];
      }
      
      // 手动构建查询字符串，兼容微信小程序
      const queryParts = [];
      
      // 添加用户ID参数
      queryParts.push(`userId=${userId}`);
      
      if (params.page) queryParts.push(`page=${params.page}`);
      if (params.size) queryParts.push(`size=${params.size}`);
      if (params.questionId) queryParts.push(`questionId=${params.questionId}`);
      if (params.keyword) queryParts.push(`keyword=${encodeURIComponent(params.keyword)}`);
      
      const queryString = queryParts.length > 0 ? '?' + queryParts.join('&') : '';
      const url = `/wjq/note/list${queryString}`;
      
      console.log('发送请求到:', url);
      console.log('查询参数:', queryParts);
      
      const res = await http.get(url);
      
      console.log('收到响应:', res);
      
      // 处理响应数据结构
      let notesData = [];
      
      if (res && res.code === 200) {
        // 如果响应直接包含数据
        if (res.rows && Array.isArray(res.rows)) {
          notesData = res.rows;
        } else if (res.data && Array.isArray(res.data)) {
          notesData = res.data;
        } else if (Array.isArray(res)) {
          notesData = res;
        }
      } else if (res && res.data) {
        // 如果响应包装在data字段中
        if (res.data.rows && Array.isArray(res.data.rows)) {
          notesData = res.data.rows;
        } else if (Array.isArray(res.data)) {
          notesData = res.data;
        }
      }
      
      console.log('解析后的笔记数据:', notesData);
      
      if (notesData.length > 0) {
        return notesData.map(note => ({
          id: note.id,
          questionId: note.questionId || note.question_id,
          content: note.content || '',
          createTime: note.createTime || note.create_time || '',
          updateTime: note.updateTime || note.update_time || '',
          questionTitle: note.questionTitle || note.question_title || '',
          questionContent: note.questionContent || note.question_content || ''
        }));
      }
      
      return [];
    } catch (error) {
      console.error('获取笔记列表失败:', error);
      return [];
    }
  }

  /**
   * 保存笔记
   * @param {Object} noteData 笔记数据
   * @returns {Promise<Object>} 保存结果
   */
  async saveNote(noteData) {
    if (!noteData.questionId || !noteData.content) {
      throw new Error('题目ID和笔记内容不能为空');
    }

    try {
      const res = await http.post('/wjq/note', {
        questionId: noteData.questionId,
        content: noteData.content,
        userId: noteData.userId
      });
      
      return res;
    } catch (error) {
      console.error('保存笔记失败:', error);
      throw error;
    }
  }

  /**
   * 更新笔记
   * @param {Object} noteData 笔记数据
   * @returns {Promise<Object>} 更新结果
   */
  async updateNote(noteData) {
    if (!noteData.id || !noteData.content) {
      throw new Error('笔记ID和内容不能为空');
    }

    try {
      const res = await http.put('/wjq/note/update', {
        id: noteData.id,
        content: noteData.content
      });
      
      return res;
    } catch (error) {
      console.error('更新笔记失败:', error);
      throw error;
    }
  }

  /**
   * 删除笔记
   * @param {string|number} questionId 题目ID
   * @returns {Promise<Object>} 删除结果
   */
  async deleteNote(questionId) {
    if (!questionId) {
      throw new Error('题目ID不能为空');
    }

    try {
      const res = await http.post('/wjq/note/delete', {
        questionId: questionId
      });
      
      return res;
    } catch (error) {
      console.error('删除笔记失败:', error);
      throw error;
    }
  }

  /**
   * 批量删除笔记
   * @param {Array} noteIds 笔记ID数组
   * @returns {Promise<Object>} 删除结果
   */
  async batchDeleteNotes(noteIds) {
    if (!Array.isArray(noteIds) || noteIds.length === 0) {
      throw new Error('笔记ID数组不能为空');
    }

    try {
      const res = await http.post('/wjq/note/batchDelete', {
        noteIds: noteIds
      });
      
      return res;
    } catch (error) {
      console.error('批量删除笔记失败:', error);
      throw error;
    }
  }

  /**
   * 搜索笔记
   * @param {string} keyword 搜索关键词
   * @param {Object} params 其他参数
   * @returns {Promise<Array>} 搜索结果
   */
  async searchNotes(keyword, params = {}) {
    if (!keyword) {
      return [];
    }

    try {
      // 获取当前用户ID
      const { getUserId } = require('./userManager.js');
      const userId = getUserId();
      
      if (!userId) {
        console.warn('用户未登录，无法搜索笔记');
        return [];
      }
      
      const searchParams = {
        keyword: keyword,
        userId: userId,
        ...params
      };
      
      const res = await http.post('/wjq/note/search', searchParams);
      
      console.log('搜索响应:', res);
      
      // 处理响应数据结构
      let notesData = [];
      
      if (res && res.code === 200) {
        // 如果响应直接包含数据
        if (res.rows && Array.isArray(res.rows)) {
          notesData = res.rows;
        } else if (res.data && Array.isArray(res.data)) {
          notesData = res.data;
        } else if (Array.isArray(res)) {
          notesData = res;
        }
      } else if (res && res.data) {
        // 如果响应包装在data字段中
        if (res.data.rows && Array.isArray(res.data.rows)) {
          notesData = res.data.rows;
        } else if (Array.isArray(res.data)) {
          notesData = res.data;
        }
      }
      
      console.log('解析后的搜索数据:', notesData);
      
      if (notesData.length > 0) {
        return notesData.map(note => ({
          id: note.id,
          questionId: note.questionId || note.question_id,
          content: note.content || '',
          createTime: note.createTime || note.create_time || '',
          updateTime: note.updateTime || note.update_time || '',
          questionTitle: note.questionTitle || note.question_title || '',
          questionContent: note.questionContent || note.question_content || ''
        }));
      }
      
      return [];
    } catch (error) {
      console.error('搜索笔记失败:', error);
      return [];
    }
  }
}

// 创建单例实例
const noteService = new NoteService();

module.exports = {
  noteService,
  NoteService
};
